﻿using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Globalization;
using System.Text;
using System.Web.UI.WebControls;

using Sunyi.Project.WebPoint.BusinessLogic;
using Sunyi.Project.WebPoint.Common;
using Sunyi.Project.WebPoint.DataContract;
using Sunyi.Project.WebPoint.Resource;
using Sunyi.Project.WebPoint.WebControl;

using ActivitySystem.BusinessLogic;
using ActivitySystem.DataContract;
using ActivitySystem.Common;

namespace ActivitySystem.Web.Activity
{
    public partial class List : WebPointPage
    {
        private ActivityManager activityManager = new ActivityManager();
        private UserManager userManager = new UserManager();
        private ParticipationManager participationManager = new ParticipationManager();
        private ActivityTypeManager activityTypeManager = new ActivityTypeManager();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    InitializeControlValues();

                    Search();
                }
                catch (Exception ex)
                {
                    ExceptionHandler.Handle(this, ex);
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                gvActivity.PageIndex = 0;
                Search();
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(this, ex);
            }
        }

        protected void gvAuditLog_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                gvActivity.PageIndex = e.NewPageIndex;
                Search();
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(this, ex);
            }
        }

        #region Private Method

        private void InitializeControlValues()
        {
            tbxStartTime.Text = DateTime.Now.ToShortDateString();

            Collection<ActivityType> activityTypes = activityTypeManager.SelectAll();
            ddlActivityType.DataTextField = ActivitySystemGlobalConstant.Name;
            ddlActivityType.DataValueField = ActivitySystemGlobalConstant.Name;
            ddlActivityType.DataSource = activityTypes;
            ddlActivityType.DataBind();

            ListItem blankListItem = new ListItem(WebPointGlobalConstant.Dash, String.Empty);
            ddlActivityType.Items.Insert(0, blankListItem);
            ddlActivityType.SelectedIndex = 0;
        }

        private void Search()
        {
            string type = ddlActivityType.SelectedValue;
            string title = tbxTitle.Text;
            string launcher = tbxHostedBy.Text;
            DateTime date = DateTime.MinValue;

            try
            {
                date = DateTime.Parse(tbxStartTime.Text);
                tbxStartTime.BackColor = WebControlCommon.DefaultControlBackColor;
            }
            catch
            {
                this.ShowClientMessage(string.Format(WebResource.InvalidDateTimeField, tbxStartTime.ID));
                tbxStartTime.BackColor = WebControlCommon.WarningBackColor;
                return;
            }

            if (gvActivity.PageIndex == 0)
            {
                gvActivity.TotalCount = activityManager.SearchCount(type, title, launcher, date);
            }

            DataTable dataTable = new DataTable();
            dataTable.Columns.AddRange(new DataColumn[]{
                new DataColumn(WebPointGlobalConstant.Id),
                new DataColumn(ActivitySystemGlobalConstant.Title),
                new DataColumn(ActivitySystemGlobalConstant.UserCount),
                new DataColumn(ActivitySystemGlobalConstant.StartTime),
                new DataColumn(ActivitySystemGlobalConstant.EndTime),
                new DataColumn(ActivitySystemGlobalConstant.Type),
                new DataColumn(ActivitySystemGlobalConstant.Launcher)
            });

            var activities = activityManager.Search(type, title, launcher, date, gvActivity.PageIndex, gvActivity.PageSize);
            foreach (var activity in activities)
            {
                string userName = userManager.Select(activity.LauncherId).UserName;

                int participtionCount = 0;
                foreach (var participationId in activity.Participations)
                {
                    var participation = participationManager.Select(participationId);
                    participtionCount += participation.Fellow + 1;
                }

                StringBuilder sbActivityTypes = new StringBuilder();
                foreach (Guid activityTypeId in activity.ActivityTypes)
                {
                    ActivityType activityType = activityTypeManager.Select(activityTypeId);
                    sbActivityTypes.Append(activityType.Name);
                    sbActivityTypes.Append(WebPointGlobalConstant.Comma);
                    sbActivityTypes.Append(WebPointGlobalConstant.Space);
                }
                string activityTypes = sbActivityTypes.ToString();
                activityTypes = activityTypes.TrimEnd(WebPointGlobalConstant.Space.ToCharArray());
                activityTypes = activityTypes.TrimEnd(WebPointGlobalConstant.Comma.ToCharArray());

                dataTable.Rows.Add(activity.Id, activity.Title, participtionCount,
                    activity.StartTime.ToString(ActivitySystemGlobalConstant.TimeEditFormatString, CultureInfo.InvariantCulture),
                    activity.EndTime.ToString(ActivitySystemGlobalConstant.TimeEditFormatString, CultureInfo.InvariantCulture),
                    activityTypes, userName);
            }

            gvActivity.DataSource = dataTable;
            gvActivity.DataBind();

            if (!Page.IsPostBack)
            {
                AuditLogger.Write(AuditLogOperationCode.Search, this.GetType().Name, type, title, launcher, date, gvActivity.PageIndex, gvActivity.PageSize);
            }
        }

        #endregion

        #region WebPointPage Member

        protected override void ApplyPermission()
        {

        }

        #endregion
    }
}